import axios from 'axios'
import Vue from 'vue'
import router from '@/router'
import utils from '@/utils/parse.js'

//axios.create()指定请求的基础url信息 
const  http=axios.create({
    // baseURL:'http://120.27.244.107:8080'
    baseURL:'http://localhost:8080'
})

//请求拦截器，config是当前请求的所有请求信息
http.interceptors.request.use(config=>{
    let accessToken= Vue.$cookies.get('access_token')
    if(accessToken&&accessToken.trim()){
        config.headers['Authorization']=`Bearer ${accessToken}`
    }
    return config;
}, err => Promise.reject(err))
/**
 * response=>{}表示一切正常，response是服务器端返回的数据
 */
http.interceptors.response.use(response=>{
    return response;
},err=>{
    let status= err.response.status//获取错误的状态码
    if(status===401){
        Vue.$cookies.remove('access_token')
        Vue.$cookies.remove('refresh_token')
        Vue.$cookies.remove('username')
        router.push('/login')
    }else if(status===586){
        //要到服务器换取新的token
         //表示当前这个错误请求的所有的请求信息
         //获取他的作用就是当我们换了新的access_token后将该请求再发一遍

        let preRequest=  err.config //刚刚失败的那次请求
        let refreshToken=Vue.$cookies.get('refresh_token')
        if(refreshToken&&refreshToken.trim()){
            // 判断access_token有没有过期，因为可能是上一个请求交换回来的新的token
            let at=Vue.$cookies.get('access_token')
            if(at&&at.trim()){
                try{
                    let payload =utils.jwtClaim(at);
                    let exp=payload.exp//过期时间，秒数
                    let currentTime= Math.floor(new Date().getTime() / 1000) 
                    if(exp - currentTime >0){
                       
                        http(preRequest)
                    }else{
                    
                        http.post('/user/refresh/token',{
                             refreshToken
                            })
                            .then(res=>{//拿到了新的token
                                let data=res.data.data
                                //重新设置到cookie中
                                Vue.$cookies.set('access_token',data)
                                http(preRequest)
                            })
                    }
                }catch(err){
                    Vue.$cookies.remove('access_token')
                    Vue.$cookies.remove('refresh_token')
                    Vue.$cookies.remove('username')
                    router.push('/login')
                }
            
            }else{
            Vue.$cookies.remove('access_token')
            Vue.$cookies.remove('refresh_token')
            Vue.$cookies.remove('username')
            router.push('/login')
            }
        }else{//也可能没有了
            Vue.$cookies.remove('access_token')
            Vue.$cookies.remove('refresh_token')
            Vue.$cookies.remove('username')
            router.push('/login')
       
        }

    }
    
})

export default http